<?php


function returnData($code,$msg,$data=''){
    return json_encode([
        'code'=>$code,
        'msg'=>$msg,
        'data'=>$data
    ]);
}

/**
 * 删除数组中没有子数组的元素
 * @param $array 二维数组
 * @param $field 子数组索引名
 * @return array
 */

function unsetArrayNotSonArray($array,$field){

    foreach ($array as $k=>$v){

        if(!isset($v[$field])){

            unset($array[$k]);
        }

    }

    return $array;
}


/**
 * 返回数组中指定的一列
 * @param $input            需要取出数组列的多维数组（或结果集）
 * @param $columnKey        需要返回值的列，它可以是索引数组的列索引，或者是关联数组的列的键。 也可以是NULL，此时将返回整个数组（配合index_key参数来重置数组键的时候，非常管用）
 * @param null $indexKey    作为返回数组的索引/键的列，它可以是该列的整数索引，或者字符串键值。
 * @return array            返回值
 */
function _array_column($input, $columnKey, $indexKey = null)
{
    if (!function_exists('array_column')) {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
        $indexKeyIsNull = (is_null($indexKey)) ? true : false;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
        $result = array();
        foreach ((array)$input as $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : null;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    } else {
        return array_column($input, $columnKey, $indexKey);
    }
}

/**
 * 获取指定团组下的id集合
 * @param teamId
 * @return array
 */
 function getDownIdToTeamId($teamId,$teamList){

    $down  = getDownLevel($teamList,$teamId,'team_id','team_pid');

    array_push($down,$teamId);

    return $down;

}

/**
 * 获取无限极分类所有下级ID
 * @param $data 无限极列表
 * @param $selfLevel 本级id
 * @param $idField  主键字段
 * @param $pidField 上级字段
 * @return array  一维数组id集合
 */
 function getDownLevel($data,$selfLevel,$idField,$pidField,$level=1){

    static $downArray = [];
    if($level == 1){
        $downArray = [];
    }
    foreach ($data as $k=> $v){

        if($v[$pidField] == $selfLevel ){
            $selfPid = $v[$idField];
            $downArray[] = $v[$idField];
            $level++;
            getDownLevel($data,$selfPid,$idField,$pidField,$level);
        }
    }

    $arr = $downArray;


    return $arr;

}

function uploadMusic($path,$filename){

    $file = request()->file($filename);

    if($file->getInfo()['type'] !='audio/mp3'){
        return 4;
    }
    $info = $file->rule('uniqid')->validate(['size'=>200*1024*1024,'ext'=>'mp3'])->move($path);

    if($info){
        return $info;
    }else{
        $this->error($file->getError());
    }
}

/**
 * 上传单图
 */
function upload($path,$filename){

    $file = request()->file($filename);

    $info = $file->rule('uniqid')->validate(['size'=>200*1024*1024,'ext'=>'doc,txt,xls,docx,xlsx,ppsx,pptm'])->move($path);

    if($info){
        return $info;
    }else{
        $this->error($file->getError());
    }
}

//框架多图上传
function arrUpload($path,$filename){

    $files = request()->file($filename);
    $path_list = '';
    foreach($files as $file){

        $info = $file->rule('uniqid')->validate(['size'=>2*1024*1024,'ext'=>'jpg,png,gif'])->move($path);
        if($info){

            $path_list[] = $info->getSaveName();
        }else{

            $this->error($file->getError());
        }
    }
    return $path_list;
}




//curl请求
//$url 参数默认是自带参
function curl($URI, $params = false){

    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL, $URI);
    curl_setopt($ch, CURLOPT_NOSIGNAL, true);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 500);
    if($params){
        curl_setopt($ch,CURLOPT_POST,true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    }
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSLVERSION, 3);


    $strRes=curl_exec($ch);

    ////var_dump($strRes);
    curl_close($ch);
    return $strRes;
}


//父子关系数组整合 == 特殊情况
function fatherSonArray1($sonArr,$fatherArr,$sonkey,$fatherkey,$newkey,$del,$del1){
    //$sonArr 子数组
    //$fatherArr 父数组
    //$son 子数组键名
    //$father 父数组键名
    //$newkey 整合过的新键名
    foreach ($fatherArr as $key => $value) {
        $fatherArr[$key][$newkey]  = '';
        foreach ($sonArr as $k => $v) {

            if($v[$sonkey] == $value[$fatherkey]){
                unset($v[$del]);
                unset($v[$del1]);

                $fatherArr[$key][$newkey][]  = $v; //['creditimg_path'];
                $fatherArr[$key]['id']  = 0;
                unset($fatherArr[$key][$del1]);

            }
        }

    }

    return $fatherArr;
}


//父子关系数组整合 ===原
function fatherSonArray($sonArr,$fatherArr,$sonkey,$fatherkey,$newkey){
    //$sonArr 子数组
    //$fatherArr 父数组
    //$son 子数组键名
    //$father 父数组键名
    //$newkey 整合过的新键名
    foreach ($fatherArr as $key => $value) {
        $fatherArr[$key][$newkey]  = null;
        foreach ($sonArr as $k => $v) {

            if($v[$sonkey] == $value[$fatherkey]){

                $fatherArr[$key][$newkey][]  = $v; //['creditimg_path'];

            }
        }

    }

    return $fatherArr;
}

//检测参数名正确或缺少或空
//$post 需要检查请求的二维数组
//$par  规定好的参数名
function checkPar($post,$par){
    //检测参数名和值
    foreach ($post as $key => $value) {

        if(!in_array($key,$par)){

            return returnData(400,'参数名有误'.$key);
        }

        if(empty($value)){

            return returnData(400,'('.$key.')参数值空');

        }
    }
    //检测参数是否缺少
    foreach ($par as $key1 => $value1) {

        if(!isset($post[$value1])){

            return returnData(400,'缺少参数'.$value1);

        }
    }
    return '1';
}






/**
 **base64单图上传储存方法
 **$imgbase64 base64图片数据
 **$path  图片保存的路径
 * type 1已去掉头部信息，2未去掉
 **/
function base64_img($imgbase64,$path,$type=1){
    if($type == 2){

        $basestr = explode(',',$imgbase64);
        $img  = base64_decode($basestr[1]);

    }else{
        $img  = base64_decode($imgbase64);
    }


    //保存图片到指定路径
    if(file_put_contents($path,$img)){

        return true;
    }else{
        return false;
    }


}





/**
 **base64上传储存方法
 **$imgbase64 去头base64图片数据
 **$path  图片保存的路径
 **$type  模式1是已经去掉头信息的 /模式2是未去头信息 图片与图片之间|分割  头信息和数组,分割
 **/
function base64_upload($imgbase64,$path,$type='1'){

    if($type==2){
        if(!is_array($imgbase64)){

            $baseArr = explode('|',$imgbase64);
        }else{
            $baseArr = array_filter($imgbase64);
        }



        $imgbase64 = array();

        foreach ($baseArr as $key => $value) {

            $imgbase64[]= explode(',', $value)[1];


        }
    }


    if(!is_array($imgbase64)){
        $imgbase64 = explode(',', $imgbase64);
    }

    if(is_array($imgbase64) && !empty($imgbase64)){

        foreach ($imgbase64 as $key => $value) {

            $newstr = base64_decode($value);
            $p = './';
            $newpath = $path.date('YmdHis',time()).rand(1001,9999).'.jpg';

            if(file_put_contents($p.$newpath,$newstr)){
                Cut($newpath,750,400);
                $pathArr[$key] = $newpath;


            }
        }



        return $pathArr;
    }
}


// 正则匹配url
//@url
function regularUrl($url){

    return $string =  eregi_replace("http://([^ ,\r\n]*)","<a href=\\0 >\\0</a>",$url);
}




/**
 * 无限极递归
 * @param $list  无限极表数据
 * @param string $pk  主键
 * @param string $pid  上级id
 * @param string $child 新key
 * @param int $root
 * @return array
 */
function make_tree($list,$pk='c_id',$pid='c_pid',$child='son',$root=0){
    $tree=array();
    $packData=array();
    foreach ($list as $data) {
//转换为带有主键id的数组
        $packData[$data[$pk]] = $data; //$packData[1]=$data; $packData[2]=$data
    }
    foreach ($packData as $key =>$val){
        if($val[$pid]==$root){ //代表跟节点
            $tree[]= &$packData[$key];
        }else{
//找到其父类
            $packData[$val[$pid]][$child][]= &$packData[$key];
        }
    }
    return $tree;
}


/**
 * 将xml转换为数组
 * @param $xml  需要转化的xml
 * @return mixed
 */
function xml_to_array($xml){
    $ob = simplexml_load_string($xml);
    $json = json_encode($ob);
    $array = json_decode($json, true);
    return $array;
}


/**
 * 将数组转化成xml
 * @param $data 需要转化的数组
 * @return string
 */
//function data_to_xml($data){
//    if (is_object($data)) {
//        $data = get_object_vars($data);
//    }
//    $xml = '';
//    foreach ($data as $key => $val) {
//        if (is_null($val)) {
//            $xml .= "<$key/>\n";
//        } else {
//            if (!is_numeric($key)) {
//                $xml .= "<$key>";
//            }
//            $xml .= (is_array($val) || is_object($val)) ? self::data_to_xml($val) : $val;
//            if (!is_numeric($key)) {
//                $xml .= "</$key>";
//            }
//        }
//    }
//    return $xml;
//}


/**
 * PHP post请求之发送XML数据
 * @param $url 请求的URL
 * @param $xmlData
 * @return mixed
 */
function xml_post_request($url, $xmlData){
    $header[] = "Content-type: text/xml";        //定义content-type为xml,注意是数组
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    }
    curl_close($ch);
    return $response;
}


/**
 * PHP post请求之发送Json对象数据
 *
 * @param $url 请求url
 * @param $jsonStr 发送的json字符串
 * @return array
 */
function http_post_json($url, $jsonStr)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        )
    );
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    return array($httpCode, $response);
}

//冒泡排序（数组排序）
function bubble_sort($array)
{
    $count = count($array);
    if ($count <= 0) return false;

    for($i=0; $i<$count; $i++){
        for($j=$count-1; $j>$i; $j--){
            if ($array[$j] < $array[$j-1]){
                $tmp = $array[$j];
                $array[$j] = $array[$j-1];
                $array[$j-1] = $tmp;
            }
        }
    }
    return $array;
}


/**
 * 获得用户的真实IP地址
 *
 * @access public
 * @return string
 */
function real_ip()
{
    $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else { $realip = getenv('REMOTE_ADDR');
        }
    }
    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    return $realip;
}

/**
 * @uses 根据生日计算年龄，年龄的格式是：2016-09-23
 * @param string $birthday
 * @return string|number
 */
 function calcAge($birthday) {
    $iage = 0;
    if (!empty($birthday)) {
        $year = date('Y',strtotime($birthday));
        $month = date('m',strtotime($birthday));
        $day = date('d',strtotime($birthday));

        $now_year = date('Y');
        $now_month = date('m');
        $now_day = date('d');

        if ($now_year > $year) {
            $iage = $now_year - $year - 1;
            if ($now_month > $month) {
                $iage++;
            } else if ($now_month == $month) {
                if ($now_day >= $day) {
                    $iage++;
                }
            }
        }
    }
    return $iage;
}

/**
 * @uses 根据生日计算年龄，年龄的格式是：2016-09-23
 * @param string $birthday
 * @return string|number 返回是4岁3个月
 */
function calcAge_($birthday) {
    $iage = ['year'=> 0 ,'month'=> 0];
    if (!empty($birthday)) {
        $year = date('Y',strtotime($birthday));
        $month = date('m',strtotime($birthday));

        $now_year = date('Y');
        $now_month = date('m');

        if ($now_year > $year) {
            $iage['year'] = $now_year - $year - 1;
            $iage['month'] = $month;

            if ($now_month > $month) {
                $iage['year']++;
                $iage['month'] = $now_month-$month;
            }

        }else{

            $iage['month'] = ($now_month-$month)?:1;
        }
    }

    return $iage;
}

/**
 * 判断当前服务器系统
 * @return string
 */
function getOS(){
    if (PATH_SEPARATOR == ':') {
        return 'Linux';
    } else {
        return 'Windows';
    }
}


//获取用户ip地址
function getIPaddress(){
    $unknown = 'unknown';
    if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown) ) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if ( isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) ) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    /*
    处理多层代理的情况
    或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
    */
    if (false !== strpos($ip, ','))
        $ip = reset(explode(',', $ip));
    return $ip;


}

//时间轴
function tranTime($time) {
    date_default_timezone_set("PRC");
    $rtime = date("m-d H:i",$time);
    $htime = date("H:i",$time);
    $ymd=date('Y-m-d H:i:s',$time);

    $time = time() - $time;

    if ($time < 60) {
        $str = '刚刚';
    }
    elseif ($time < 60 * 60) {
        $min = floor($time/60);
        $str = $min.'分钟前';
    }
    elseif ($time < 60 * 60 * 24) {
        $h = floor($time/(60*60));
        $str = $h.'小时前 '.$htime;
    }
    elseif ($time < 60 * 60 * 24 * 3) {
        $d = floor($time/(60*60*24));
        if($d==1)
            $str = '昨天 '.$rtime;
        else
            $str = '前天 '.$rtime;
    }
    else {
        $str = $ymd;
    }
    return $str;
}



/**
 * 微信模板消息
 * @msgid 模板消息的id
 * @$openid 接受消息的微信用户openid
 * @appid 微信公众商户的id
 * @secret 微信公众号秘钥
 * @data   消息内容二维数组
 */

function wxSendMsg($msgid,$openid,$appid,$secret,$data){

    $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
    $arr = json_decode(file_get_contents($url),1);
    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$arr['access_token'];
    $date=date('Y-m-d H:i:s',time());
    $template_msg=array('touser'=>$openid,
        'template_id'=>$msgid,'topcolor'=>'#FF0000',
        'data'=>$data);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($template_msg)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($template_msg));
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 计算指定经纬度附近5公里
 * @lng 当前的经纬
 * @lat 当前纬度
 * @distance 附近公里数
 */
function returnSquarePoint($lng, $lat,$distance = 0.5){  //计算经纬度距离
    $earth_radius = 6371;
    $dlng =  2 * asin(sin($distance / (2 * $earth_radius)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);
    $dlat = $distance/$earth_radius;
    $dlat = rad2deg($dlat);
    return array(
        'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
        'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
        'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
        'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
    );
}


//根据经纬度获取周边信息
function domap_list($gps_position,$distance){
    date_default_timezone_set('prc');
    $arr = explode(",",$gps_position);
    $lat = $arr[0];
    $lon = $arr[1];
    $squares = returnSquarePoint($lon, $lat,$distance);
    ////var_dump($squares);exit();
    $arr=array();
    $info_sql = "select  * ,CONCAT_WS(',',mapmode_lat,mapmode_lng) as gps from mapmodeinfo where mapmode_lat<>0 and mapmode_lat>{$squares['right-bottom']['lat']} and mapmode_lat<{$squares['left-top']['lat']} 
		and mapmode_lng<{$squares['left-top']['lng']} and mapmode_lng>{$squares['right-bottom']['lng']} and mapmode_status='0'"; //查出当前位置周边信息
    $res = $this-> db->query($info_sql);
    foreach ($res->result_array() as $row)
    {
        $arr[]=$row;
    }

    return $arr;

}


/**
 * 微信授权登录
 * @appid 微信商户id
 * @secret 微信商户的秘钥
 * @ThisUrl 回调地址
 * @goUrl 	跳转的id
 */
function wechatUser($appid,$secret,$ThisUrl,$goUrl){
    header("Content-type:text/html;charset=utf-8");
    echo '<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">';

    echo '<style>
                body{
                    margin:0;
                    padding:10px;
                    background-color:#E1E0DE;
                    font:12px/18px "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
                }
                p{
                    font-size:16px;
                    line-height:1.3em;
                    color:#000;
                    text-align:center;
                    font-weight:bold;
                    text-shadow:0px 1px 0px #EFEFED;
                    margin:0px;
                    margin-top:20px;
                    margin-bottom:18px;
                }
            </style>';
    echo "<body><p>";
//	$ThisUrl = "http://www.bdniao.com/Home/Login/weixin";
//	$appid ="wx45243233d94ffcaf";
//	$secret ="4c5fe270110e3b6ea05e110a72494f34";

    if(empty($_GET['code'])){
        // header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".urlencode($ThisUrl)."&response_type=CODE&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".urlencode($ThisUrl)."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect ");

        exit;
    }
    $ch = curl_init();//初始化curl
    curl_setopt($ch,CURLOPT_URL,"https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$_GET['code']."&grant_type=authorization_code");
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上

    $AccessToken = curl_exec($ch);
    $AccessToken = json_decode($AccessToken,true);
    if(empty($AccessToken['access_token'])){
        //var_dump($AccessToken);
        echo "Token Error";
        exit;
    }


    $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
    $arr = json_decode(file_get_contents($url),1);

    //是否要查询公众号的用户列表
    /*
    $ch = curl_init();//初始化curl
    curl_setopt($ch,CURLOPT_URL,"https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$arr['access_token']);
   // curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    $openid_list = curl_exec($ch);

    $openid_list = json_encode($openid_list,true);
    // //var_dump($openid_list);die;
    */

    $ch = curl_init();//初始化curl
    curl_setopt($ch,CURLOPT_URL,"https://api.weixin.qq.com/sns/userinfo?access_token=".$AccessToken['access_token']."&openid=".$AccessToken['openid']."&lang=zh_CN");
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    $UserInfo = curl_exec($ch);
    $UserInfo = json_decode($UserInfo,true);

    if(empty($UserInfo['openid'])){
        //var_dump($UserInfo);
        echo "OpenId Error";
        exit;
    }

    echo "<pre>";
    ////var_dump($UserInfo);
    //echo $UserInfo['nickname'];
    $UserInfo=json_encode($UserInfo);
    // dump($UserInfo);die;
    header("Location:".$goUrl."?info=$UserInfo");
    echo "</pre>";
    echo '</p></body>';
}


/**
 * 文章匹配url 转成实际连接
 * @str 文章内容
 */

function turnUrl($str){

    preg_match_all('#(http(s)?://)+(.*)(.com)+#U',$str,$match);

    foreach($match[0] as $value){
        $strReplace='<a href=\''.$value.'\'>'.' '.$value.' '."</a>";
        $str=str_replace($strReplace,$value,$str);//文本中存在重复的url 且进行了一次替换的时候把先前的替换回来重新替换一次
        $str=str_replace($value,$strReplace,$str);
    }

    return  $str;
}


/**
 * 文章匹配img src替换掉路径
 */

function updateImgSrc($str){

    return removeUrl($str,"\/public");

}



 function removeUrl($str = '',$fil = '')
 {
     $preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';//匹配img标签的正则表达式
     preg_match_all($preg, $str, $allImg);//这里匹配所有的img
     $count=count($allImg[0]);

     for($i=0;$i<=$count;$i++){
         $str = preg_replace('/(<img.+src=\"?.+)('.$fil.')(.+\.(jpg|jpeg|gif|bmp|bnp|png)\"?.+>)/i',"\${1}\${3}",$str);
     }


     return $str;
 }


//取出文章内的src 放进一个数组新key里

function getImgSrc($array,$key,$newkey){


    foreach ($array as $k=>&$v){

        $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$v[$key],$match);
//        dump($match);
        $v[$newkey] = isset($match[1][0])?$match[1][0]:'';


    }

    return $array;


}

//算出本周开始到结束日期

function getWeekDay($to_day){

    $sdefaultDate = $to_day;

//$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
    $first=1;

//获取当前周的第几天 周日是 0 周一到周六是 1 - 6
    $w=date('w',strtotime($sdefaultDate));

//获取本周开始日期，如果$w是0，则表示周日，减去 6 天
    $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
//本周结束日期
    $week_end=date('Y-m-d',strtotime("$week_start +6 days"));


    return ['start'=>$week_start,'end'=>$week_end];


}

/**
 * 获取上周的开始日期和结束日期
 */
function getLastWeekDay($to_day){
    $date=$to_day;  //当前日期
    $first=1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
    $w=date('w',strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
    $now_start=date('Y-m-d',strtotime("$date -".($w ? $w - $first : 6).' days')); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
    $now_end=date('Y-m-d',strtotime("$now_start +6 days"));  //本周结束日期
    $last_start=date('Y-m-d',strtotime("$now_start - 7 days"));  //上周开始日期
    $last_end=date('Y-m-d',strtotime("$now_start - 1 days"));  //上周结束日期

    return ['start'=>$last_start,'end'=>$last_end];
}

//算两个日期中的每一个日期
function startAndEndDateToDayNum($start,$end){

    $dayNum = (strtotime($end)-strtotime($start))/24/60/60;

    for($i=0;$i<= $dayNum;$i++){

        $dateList[] = date('Y-m-d',strtotime(" +$i day",strtotime($start)));

    }

    return $dateList;

}

//查出来的一周数据,进行对没有记录的天数赋值
/**
 * @param $res  一周的数据
 * @param $dateList  一周的日期
 * @param $key  按哪个字段来重组
 */
function WeekData($res,$dateList,$key){

    foreach ($dateList as $k=>$v){
        $newdata[$k] = 0;
        foreach ($res as $k1=>$v1){
            $d = date('Y-m-d',strtotime($v1[$key]));
            if(in_array($v,$v1)){
                $newdata[$k] = $v1['timelong'];
            }


        }

    }


    return $newdata;


}


//查出来的一周数据,进行对没有记录的天数赋值
/**
 * @param $res  一周的数据
 * @param $dateList  一周的日期
 * @param $key  按哪个字段来重组
 */
function WeekDataForDateIsKey($res,$dateList,$key,$field){


    foreach ($dateList as $k=>$v){
        $newdata[$k] = 0;


        foreach ($res as $k1=>$v1){

            if($v==$v1[$key]){
                $newdata[$k] = $v1[$field];
            }


        }

    }


    return $newdata;


}


//算出两个日期之间月份数
function startAndEndDateToMonthNum($start,$end){
    $date1_stamp=strtotime($start);
    $date2_stamp=strtotime($end);
    list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));
    list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));
    return abs($date_1['y']-$date_2['y'])*12 +$date_2['m']-$date_1['m'];

}


//算出两个日期之间年份集合
function startAndEndDateToYearNum($start,$end){
    $date1_stamp=strtotime($start);
    $date2_stamp=strtotime($end);
    $num = date('Y',$date2_stamp)-date('Y',$date1_stamp);

    for($i=0;$i<=$num;$i++){

       $year[] = date('Y',$date1_stamp)+$i;
    }

    return $year;

}


//计算出前6个月的月份集合
function getMonth($mNum){

    $nowd = date("Y-m-1");
    for ($i=0;$i<=$mNum;$i++){
        $month[] = date('Y-m',strtotime('-'.$i."month $nowd"));
    }

    return $month;
}

/**
 * 算指定日期间相隔多少个月份
 * @param $date1 开始日期
 * @param $date2 结束日期
 * @return number
 */

 function getMonthNum($date1,$date2){
    $date1_stamp=strtotime($date1);
    $date2_stamp=strtotime($date2);
    list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));
    list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));
    return abs($date_1['y']-$date_2['y'])*12 +$date_2['m']-$date_1['m'];
}


/**
 * 算出指定日期之间每个月的第一天周几，多少天数
 * @param $start  开始日期
 * @param $mnum   多少个月份
 * @return mixed  返回二位数组
 */

 function getDateData($start,$mnum){

    for($i=0;$i<=$mnum;$i++){
        //日期

        $date[$i]['date'] = date("Y-m-d", strtotime("+$i months", strtotime($start)));
        $m = date("m",strtotime($date[$i]['date']));
        $y = date("Y",strtotime($date[$i]['date']));
        //每月的天数
        $date[$i]['daynum'] = cal_days_in_month(CAL_GREGORIAN, $m, $y);
        //每月第一天周几
        $date[$i]['w'] = date('w',strtotime(date("Y-m-01",strtotime($date[$i]['date']))));
        $date[$i]['date'] = date("Y-m", strtotime("+$i months", strtotime($start)));


    }

    return $date;

}

//计算出两个日期之前的所有月份
function DateForMonth($start,$end){

    $num = getMonthNum($start,$end);
    for ($i=0;$i<=$num;$i++){
        $m[] = date('Y-m',strtotime('+'.$i."month $start"));
    }

    return $m;
}


/**
 * 获取用户的设备端类型
 *
 */

function getDevice()
{
    //获取USER AGENT
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    //分析数据
    $is_pc = (strpos($agent, 'windows nt')) ? true : false;
    $is_iphone = (strpos($agent, 'iphone')) ? true : false;
    $is_ipad = (strpos($agent, 'ipad')) ? true : false;
    $is_android = (strpos($agent, 'android')) ? true : false;
    $mac = (strpos($agent, 'mac')) ? true : false;

    //输出数据
    if ($is_pc) {
        return 'PC';
    }
    if ($is_iphone) {
        return "iPhone";
    }
    if ($is_ipad) {
        return "iPad";
    }
    if ($is_android) {
        return "Android";
    }
    if($mac){
        return 'mac';
    }

}


/**
 * 获取浏览器类型
 */
function getBrowser(){
    //获取USER AGENT
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (strpos($agent, 'micromessenger')) {
        return 'wx';
    }elseif (strpos($agent, 'qqbrowser')) {
        return 'qq';
    }elseif(strpos($agent, 'chrome')){
        return 'chrome';
    }elseif (strpos($agent, 'firefox')){
        return 'firefox';
    }elseif (strpos($agent, 'ucbrowser')){
        return 'uc';
    }elseif (strpos($agent, 'baiduboxapp')){
        return 'baidu';
    }else{
        return '未检测到浏览器类型';
    }
}

/**
 * 将json写进js文件
 */
function writeFile($array,$path){

    $arr =json_encode($array,JSON_UNESCAPED_UNICODE);

    $res = file_put_contents('.'.$path,"\n".' var $city='. $arr);
    return $res;
}

/**
 * 写入数据到文件
 */

function writeDataFile($data,$path){
    $res = file_put_contents('.'.$path,'2017-07-05写入了一段数据是：'.var_export($data,true)."\r\n",FILE_APPEND);
    return $res;
}

/**
 * 获取xml文件数据转成数组
 */
function getXmlFileData($url = 'http://101.37.150.196:3131/hqApplet/data/CreateXMLClass.xml'){

    $xml=simplexml_load_string(file_get_contents($url));
    $data = json_decode(json_encode($xml),TRUE);
    return $data;
    
}



/**
 * XML转数组
 * @param unknown $xml
 * @return mixed
 */
function xmlToArray($xml)
{
    //将XML转为array
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $array_data;
}

/**
 * sockopen 请求
 * @param $url
 * @param array $param
 * @author 品花
 * @date zsdate
 *   #解决fsockopen异步请求失败nginx日志报499问题 fastcgi_ignore_client_abort on;
 */
function sockopenRequest($url, $param=array()){

	$urlinfo = parse_url($url);

	$host = $urlinfo['host'];
	$path = $urlinfo['path'];
	$query = isset($param)? http_build_query($param) : '';

	$port = 80;
	$errno = 0;
	$errstr = '';
	$timeout = 10;

	$fp = fsockopen($host, $port, $errno, $errstr, $timeout);

    if(!$fp){
        return "sockopen 失败";
    }
	$out = "POST ".$path." HTTP/1.1\r\n";
	$out .= "host:".$host."\r\n";
	$out .= "content-length:".strlen($query)."\r\n";
	$out .= "content-type:application/x-www-form-urlencoded\r\n";
	$out .= "connection:close\r\n\r\n";
	$out .= $query;

    fputs($fp, $out);
    $data = fgets($fp,128);
    fclose($fp);
}

/**
 * 红包算法
 * @param $money 总金额
 * @param $number 红包个数
 * @param $max   单个红包最大上限
 * @param $min   单个红包最小上限
 * @author 品花
 * @date zsdate
 */
function redpacketsArithmetic($money_total,$num,$max,$min){

    if($money_total < $num*0.01) {
        exit('钱太少');
    }

    $rand_arr = array();
    for($i=0; $i<$num; $i++) {
        $rand = rand(1, 100);
        $rand_arr[] = $rand;
    }

    $rand_sum = array_sum($rand_arr);
    $rand_money_arr = array();
    $rand_money_arr = array_pad($rand_money_arr, $num, 0.01);  //保证每个红包至少0.01

    foreach ($rand_arr as $key => $r) {
        $rand_money = number_format($money_total*$r/$rand_sum, 2);

        if($rand_money <= 0.01 || number_format(array_sum($rand_money_arr), 2) >= number_format($money_total, 2)) {
            $rand_money_arr[$key] = 0.01;
        } else {
            $rand_money_arr[$key] = $rand_money;
        }

    }

    $max_index = $max_rand = 0;
    foreach ($rand_money_arr as $key => $rm) {
        if($rm > $max_rand) {
            $max_rand = $rm;
            $max_index = $key;
        }
    }

    unset($rand_money_arr[$max_index]);
    //这里的array_sum($rand_money_arr)一定是小于$money_total的
    $rand_money_arr[$max_index] = number_format($money_total - array_sum($rand_money_arr), 2);

    ksort($rand_money_arr);

     return $rand_money_arr;

}


/**
 * 红包算法
 * @param int $bonus_total 红包总金额
 * @param int $bonus_count 红包个数
 * @param int $bonus_type  红包类型 1=拼手气红包 0=普通红包
 * @return array
 */
function randBonus($bonus_total=0, $bonus_count=3, $bonus_type=1){

    $bonus_items  = array(); // 将要瓜分的结果

    $bonus_balance = $bonus_total; // 每次分完之后的余额

    $bonus_avg   = number_format($bonus_total/$bonus_count, 2); // 平均每个红包多少钱

    $i       = 0;

    while($i<$bonus_count){

        if($i<$bonus_count-1){

            $rand      = $bonus_type?(rand(1, $bonus_balance*100-1)/100):$bonus_avg; // 根据红包类型计算当前红包的金额
            //不能让随机金额大于余额
            while($rand >= $bonus_balance ){
                $rand      = $bonus_type?(rand(1, $bonus_balance*100-1)/100):$bonus_avg;
            }
            $bonus_items[] = sprintf("%.2f",$rand);

            $bonus_balance -= sprintf("%.2f",$rand);

        }else{

            $bonus_items[] = sprintf("%.2f",$bonus_balance) ; // 最后一个红包直接承包最后所有的金额，保证发出的总金额正确

        }

        $i++;

    }

    return $bonus_items;

}

/**
 * 二维数组根据某个值排序
 * @param $list 二维数组
 * @param $field 值字段
 */
function twoArraySort($list,$field,$type=SORT_DESC){

    array_multisort(array_column($list,$field),$type ,$list);

    return $list;
}


/**
 *二维数组分组
 * @param key    根据某个key进行分组
 * @param son   子组key名
 * @param list  二维数组
 * @param groupName  分组key名
 * @return array
 */
function arrayGroup($list,$key,$son,$groupName,$n=""){


    $res =   [];
    foreach($list as $k=>$v){
        $res[$v[$key]][$groupName]   =  $v[$key];
        if($n){
           $res[$v[$key]][$n]   =  $v[$n];
        }

        $res[$v[$key]][$son][]    =   $v;

    }
    $new =[];
    foreach ($res as $k=>&$v){

        $new[] = $v;
    }

    return $new;

}


/**
 * 中心服务获取签名
 * @param $data
 * @param $secret
 * @return string
 * @author 品花
 * @date 2019/4/17 0017 下午 5:51
 */
function getSign($data,$secret,$salt){


    ksort($data);

    $params = http_build_query($data);

    $sign = strtoupper(md5(urldecode($params . $secret .$salt)));

    return $sign;
}



/**
 * 验证签名
 * @param array $data
 * @param string $key
 * @return string
 */

function getVerifySign($data, $key)
{
    $String = formatParameters($data, false);
    //签名步骤二：在string后加入KEY
    $String = $String . "&key=" . $key;
    //签名步骤三：MD5加密
    $String = md5($String);
    //签名步骤四：所有字符转为大写
    $result = strtoupper($String);
    return $result;
}

function formatParameters($paraMap, $urlencode)
{
    $buff = "";
    ksort($paraMap);
    foreach ($paraMap as $k => $v) {
        if($k=="sign"){
            continue;
        }
        if ($urlencode) {
            $v = urlencode($v);
        }
        $buff .= $k . "=" . $v . "&";
    }
    $reqPar = "";
    if (strlen($buff) > 0) {
        $reqPar = substr($buff, 0, strlen($buff) - 1);
    }
    return $reqPar;
}



/**
 * 数组转XMl
 * @param $arr
 * @return string
 * @author 品花
 * @date mydate
 */
 function arrayToXml($arr)
{

    $str='<xml>';
    foreach($arr as $k=>$v) {
        $str.='<'.$k.'>'.$v.'</'.$k.'>';
    }
    $str.='</xml>';
    return $str;

}


/**
 * 求两个日期之间相差的天数
 * (针对1970年1月1日之后，求之前可以采用泰勒公式)
 * @param string $day1
 * @param string $day2
 * @return number
 */
function diffBetweenTwoDays ($day1, $day2)
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);

    if ($second1 < $second2) {
    $tmp = $second2;
    $second2 = $second1;
    $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}

/**
 * 获取值较小的随机数
 * @param $min
 * @param $max
 * @return int
 * @author 品花
 * @date 2019/7/17 0017 下午 5:13
 */
function getRand($min,$max) {
    $num=rand($min,$max);
    return rand($min,$num);
}



/**
 * 计算.生肖
 * @param int $year 年份
 * @return str
 */
function get_animal($year){
    $animals = array(
        '鼠', '牛', '虎', '兔', '龙', '蛇',
        '马', '羊', '猴', '鸡', '狗', '猪'
    );
    $key = ($year - 1900) % 12;
    return $animals[$key];
}


/**
 * 计算.星座
 *
 * @param int $month 月份
 * @param int $day 日期
 * @return str
 */
function get_constellation($month, $day){
    $signs = array(
        array('20'=>'宝瓶座'), array('19'=>'双鱼座'),
        array('21'=>'白羊座'), array('20'=>'金牛座'),
        array('21'=>'双子座'), array('22'=>'巨蟹座'),
        array('23'=>'狮子座'), array('23'=>'处女座'),
        array('23'=>'天秤座'), array('24'=>'天蝎座'),
        array('22'=>'射手座'), array('22'=>'摩羯座')
    );
    $key = (int)$month - 1;
    list($startSign, $signName) = each($signs[$key]);
    if( $day < $startSign ){
        $key = $month - 2 < 0 ? $month = 11 : $month -= 2;
        list($startSign, $signName) = each($signs[$key]);
    }
    return $signName;
}


function curl1($param="",$url,$path="") {
    $postUrl = $url;
    $curlPost = $param;
    $cert_path = $path;
    $ch = curl_init();                                      //初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);                 //抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);           // 增加 HTTP Header（头）里的字段
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        // 终止从服务端进行验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

    curl_setopt($ch,CURLOPT_SSLCERT,$cert_path.'/App/cert/apiclient_cert.pem'); //这个是证书的位置绝对路径
    curl_setopt($ch,CURLOPT_SSLKEY,$cert_path.'/App/cert/apiclient_key.pem'); //这个也是证书的位置绝对路径

    $data = curl_exec($ch);                                 //运行curl
    curl_close($ch);
    return $data;
}

/**是否为双数
 * @param $number
 * @return int
 */
function isDoubleNumber($number){


    return  ($number%2)!=0?0:1;
}

/**是否为大数
 * @param $number
 * @param int $start_num 对比数
 * @return int
 *
 */
function isBigNumber($number,$start_num=5){

    return $number > $start_num?1:0;
}


/**大小和
 * @param $number
 * @param int $start_num 对比数
 * @return int
 *
 */
function isBigSmallSum($number,$start_num=5){

    if($number == 11){

        return 2;
    }
    elseif($number >= $start_num){

        return 1;
    }elseif ($number < $start_num){

        return 0;
    }

}


/**11选五总和路珠大小和
 * @param $number
 * @param int $start_num 对比数
 * @return int
 *
 */
function isSYXWBigSmallSum($number,$start_num=5){

    if($number == 30){

        return 2;
    }
    elseif($number >= $start_num){

        return 1;
    }elseif ($number < $start_num){

        return 0;
    }

}


/**快3
 * @param $number
 * @param int $start_num 对比数
 * @return int
 *
 */
function isBigforKuai3($numbers,$start_num=3){

    $sum  = array_sum($numbers);

    if($numbers[0] == $numbers[1] &&  $numbers[0] == $numbers[2]  ){
        return 2;
    }
    elseif($sum >= $start_num){

        return 1;
    }elseif ($sum < $start_num){

        return 0;
    }

}


/**大小平
 * @param $number
 * @param int $start_num 对比数
 * @return int
 *
 */
function isBigSmallAvg($number,$start_num=5){


    if($number >= $start_num){

        return 1;
    }elseif ($number < $start_num){

        return 0;
    }else{

        return 2;
    }

}


/**10个数字对比龙虎
 * @param array $numbers
 * @return array
 */
function dragonTiger(array $numbers ){


    foreach($numbers as $k=>  $number){

        if($number > $numbers[(count($numbers)-1)-$k]){

            $arr[] = 1;
        }elseif($number == $numbers[(count($numbers)-1)-$k]){
            $arr[] = 2;
        }else{
            $arr[] = 0;
        }

        if(count($arr) >=5){
            break ;
        }


    }

    return $arr;
}


/**
 * 冠亚和是否为大数
 * @param array $numbers
 * @param int $start 大数参比值
 * @return int
 */
function gySumIsBigNumber(array $numbers ,$start = 10){

    $sum = $numbers[0]+$numbers[1];

    return isBigNumber($sum,$start);
}


/**冠亚和是否为双数
 * @param array $numbers
 * @return array
 */
function gySumDsDoubleNumber(array $numbers ){

    $sum = $numbers[0]+$numbers[1];

    return isDoubleNumber($sum);
}

/**5个数字对比龙虎
 * @param array $numbers
 * @return array
 */
function dragonTigerFor5(array $numbers ){

    if($numbers[0] > $numbers[4]){
        return 1;
    }elseif ($numbers[0] == $numbers[4]){

        return 2;
    }else{

        return 0;
    }

}


/**2个数字对比求龙虎
 * @param array $numbers
 * @return array
 */
function twoNumberDragonTiger($number1,$number2 ){

    if($number1 > $number2){
        return 1;
    }elseif ($number1 == $number2){

        return 2;
    }else{

        return 0;
    }

}


/**
 * 计算，杂6，半顺，顺子
 * @param $data 1纬索引数组
 * @return string
 */
function straight($data) {

    $equal = 0;
    $adjacent = 0;
    foreach($data as $k1 => $v1){
        foreach($data as $k2 => $v2){
            if($k1!=$k2){
                if($v1 == $v2){$equal+=1; $adjacent-=1;}
                if(abs($v1-$v2)==1 || abs($v1-$v2)==9){$adjacent+=1;}
            }
        }
    }
    $equal = $equal/2;
    $adjacent = $adjacent/2;
    if($adjacent == 2){

        return '顺子';
    }

    if($equal > 0){
        return '对子';
    }
    if($adjacent == 1){

        return '半顺';
    }

    return '杂六';

}

/**
 * 计算某个数字在数组中连续出现次数
 * @param $List
 * @param $number
 * @return int
 */
function consecutiveOccurrences($List,$number){

    $count = 0;
    foreach ($List as  $k => $v){
        if($v == $number &&  $count == 0){

            $count++;
        }
        if(isset($List[$k+1]) && $List[$k+1] == $v && $v==$number){

            $count++;
        }
    }

    return $count;
}


/**
 * 去掉重复值后获取数组长度
 * @param $dataList
 * @return int
 *
 */
function getLenthForUnique($dataList){

    $list = array_unique($dataList);

    return count($list);

}



/**
 * 计算数据形态关系：顺子,对子 ，半顺，杂6
 * @param $data 1纬索引数组
 * @return string
 */
function morphologicalRelationship($data) {

    $equal = 0;
    $adjacent = 0;
    foreach($data as $k1 => $v1){
        foreach($data as $k2 => $v2){
            if($k1!=$k2){
                if($v1 == $v2){$equal+=1; $adjacent-=1;}
                if(abs($v1-$v2)==1 || abs($v1-$v2)==9){$adjacent+=1;}
            }
        }
    }
    $equal = $equal/2;
    $adjacent = $adjacent/2;
    if($adjacent == 2){

        return 1;
    }

    if($equal > 0){
        return 2;
    }
    if($adjacent == 1){

        return 3;
    }

    return 4;

}


/**
 * 在一个时间段里获取总秒数和当前流逝秒数
 * @param $inTime
 * @return array
 */
function getSumAndPassingForTimePeriod($inTime){
//    $inTime = [
//        ['start'=> "01:00:30" ,'end'=> "10:00:30"],
//        ['start'=> "12:00:30" ,'end'=> "23:59:30"],
//    ];

    $now = time();
    $passing = 0;
    $sum  = 0;
    foreach($inTime as $v) {

        $sum += strtotime($v['end']) - strtotime($v['start']);

        if ($now > strtotime($v['end'])) {

            $passing += strtotime($v['end']) - strtotime($v['start']);
        } else {

            $passing += $now - strtotime($v['start']);

        }

    }

    return ['sum'=> $sum ,'passing'=>$passing];
}


/**
 * 获取当前开奖时间
 * @param $inTime  开奖时间段
 * @param int $interval  每次开奖间隔
 * @return array
 */
function getCurrentOpenTime($inTime,$interval = 60){

//    $inTime = [
//        ['start'=> "00:00:10" ,'end'=> "10:00:30"],
//        ['start'=> "12:00:00" ,'end'=> "16:59:30"],
//        ['start'=> "17:00:30" ,'end'=> "23:59:30"],
//    ];

    $now = time();
    $num = 0;
    $time = 0;
    foreach($inTime as $k=> $v) {

        $temp = strtotime($v['end']) - strtotime($v['start']);
        if($now < strtotime($v['end']) ){

            $temp +=$now - strtotime($v['end']);

        }

        $num += $n = intval($temp/$interval);

        //在开奖范围内第一次开奖的时间
        if($now- strtotime($v['start']) < $interval ){

            $time = $now -$interval;

        }
        //在重启之后当前这期开奖时间
        if($now < strtotime($v['end']) ){

            $time = strtotime($v['start'])+$n*$interval;
        }

        //在当前开奖时间段内
        if ($now > strtotime($v['start']) && $now < strtotime($v['end'])) {

            break ;
        }
        //如果还未到下一个开奖时间段
        if(isset($inTime[$k+1])){
            if($now < strtotime($inTime[$k+1]['start']) ){

                $time = strtotime($inTime[$k+1]['start']);
                break ;
            }
        }


    }


    return ['time'=> $time,'date_num'=> $num ];
}


/**
 * 获取豹子对子 三不同 号码形态
 * @param $numbers
 * @return int
 */
function numberPattern($numbers){

    if($numbers[0] == $numbers[1] && $numbers[0] == $numbers[2]){

        return 1;
    }
    if($numbers[0] == $numbers[1] || $numbers[0] == $numbers[2] ||  $numbers[1] == $numbers[2] ){

        return 2;
    }
    return 3;

}


/**
 * 随机nick
 * @return string
 */
 function random_str(){
    $nicheng_tou=array('快乐的','冷静的','醉熏的','潇洒的','糊涂的','积极的','冷酷的','深情的','粗暴的','温柔的','可爱的','愉快的','义气的','认真的','威武的','帅气的','传统的','潇洒的','漂亮的','自然的','专一的','听话的','昏睡的','狂野的','等待的','搞怪的','幽默的','魁梧的','活泼的','开心的','高兴的','超帅的','留胡子的','坦率的','直率的','轻松的','痴情的','完美的','精明的','无聊的','有魅力的','丰富的','繁荣的','饱满的','炙热的','暴躁的','碧蓝的','俊逸的','英勇的','健忘的','故意的','无心的','土豪的','朴实的','兴奋的','幸福的','淡定的','不安的','阔达的','孤独的','独特的','疯狂的','时尚的','落后的','风趣的','忧伤的','大胆的','爱笑的','矮小的','健康的','合适的','玩命的','沉默的','斯文的','香蕉','苹果','鲤鱼','鳗鱼','任性的','细心的','粗心的','大意的','甜甜的','酷酷的','健壮的','英俊的','霸气的','阳光的','默默的','大力的','孝顺的','忧虑的','着急的','紧张的','善良的','凶狠的','害怕的','重要的','危机的','欢喜的','欣慰的','满意的','跳跃的','诚心的','称心的','如意的','怡然的','娇气的','无奈的','无语的','激动的','愤怒的','美好的','感动的','激情的','激昂的','震动的','虚拟的','超级的','寒冷的','精明的','明理的','犹豫的','忧郁的','寂寞的','奋斗的','勤奋的','现代的','过时的','稳重的','热情的','含蓄的','开放的','无辜的','多情的','纯真的','拉长的','热心的','从容的','体贴的','风中的','曾经的','追寻的','儒雅的','优雅的','开朗的','外向的','内向的','清爽的','文艺的','长情的','平常的','单身的','伶俐的','高大的','懦弱的','柔弱的','爱笑的','乐观的','耍酷的','酷炫的','神勇的','年轻的','唠叨的','瘦瘦的','无情的','包容的','顺心的','畅快的','舒适的','靓丽的','负责的','背后的','简单的','谦让的','彩色的','缥缈的','欢呼的','生动的','复杂的','慈祥的','仁爱的','魔幻的','虚幻的','淡然的','受伤的','雪白的','高高的','糟糕的','顺利的','闪闪的','羞涩的','缓慢的','迅速的','优秀的','聪明的','含糊的','俏皮的','淡淡的','坚强的','平淡的','欣喜的','能干的','灵巧的','友好的','机智的','机灵的','正直的','谨慎的','俭朴的','殷勤的','虚心的','辛勤的','自觉的','无私的','无限的','踏实的','老实的','现实的','可靠的','务实的','拼搏的','个性的','粗犷的','活力的','成就的','勤劳的','单纯的','落寞的','朴素的','悲凉的','忧心的','洁净的','清秀的','自由的','小巧的','单薄的','贪玩的','刻苦的','干净的','壮观的','和谐的','文静的','调皮的','害羞的','安详的','自信的','端庄的','坚定的','美满的','舒心的','温暖的','专注的','勤恳的','美丽的','腼腆的','优美的','甜美的','甜蜜的','整齐的','动人的','典雅的','尊敬的','舒服的','妩媚的','秀丽的','喜悦的','甜美的','彪壮的','强健的','大方的','俊秀的','聪慧的','迷人的','陶醉的','悦耳的','动听的','明亮的','结实的','魁梧的','标致的','清脆的','敏感的','光亮的','大气的','老迟到的','知性的','冷傲的','呆萌的','野性的','隐形的','笑点低的','微笑的','笨笨的','难过的','沉静的','火星上的','失眠的','安静的','纯情的','要减肥的','迷路的','烂漫的','哭泣的','贤惠的','苗条的','温婉的','发嗲的','会撒娇的','贪玩的','执着的','眯眯眼的','花痴的','想人陪的','眼睛大的','高贵的','傲娇的','心灵美的','爱撒娇的','细腻的','天真的','怕黑的','感性的','飘逸的','怕孤独的','忐忑的','高挑的','傻傻的','冷艳的','爱听歌的','还单身的','怕孤单的','懵懂的');

    $nicheng_wei=array('嚓茶','凉面','便当','毛豆','花生','可乐','灯泡','哈密瓜','野狼','背包','眼神','缘分','雪碧','人生','牛排','蚂蚁','飞鸟','灰狼','斑马','汉堡','悟空','巨人','绿茶','自行车','保温杯','大碗','墨镜','魔镜','煎饼','月饼','月亮','星星','芝麻','啤酒','玫瑰','大叔','小伙','哈密瓜，数据线','太阳','树叶','芹菜','黄蜂','蜜粉','蜜蜂','信封','西装','外套','裙子','大象','猫咪','母鸡','路灯','蓝天','白云','星月','彩虹','微笑','摩托','板栗','高山','大地','大树','电灯胆','砖头','楼房','水池','鸡翅','蜻蜓','红牛','咖啡','机器猫','枕头','大船','诺言','钢笔','刺猬','天空','飞机','大炮','冬天','洋葱','春天','夏天','秋天','冬日','航空','毛衣','豌豆','黑米','玉米','眼睛','老鼠','白羊','帅哥','美女','季节','鲜花','服饰','裙子','白开水','秀发','大山','火车','汽车','歌曲','舞蹈','老师','导师','方盒','大米','麦片','水杯','水壶','手套','鞋子','自行车','鼠标','手机','电脑','书本','奇迹','身影','香烟','夕阳','台灯','宝贝','未来','皮带','钥匙','心锁','故事','花瓣','滑板','画笔','画板','学姐','店员','电源','饼干','宝马','过客','大白','时光','石头','钻石','河马','犀牛','西牛','绿草','抽屉','柜子','往事','寒风','路人','橘子','耳机','鸵鸟','朋友','苗条','铅笔','钢笔','硬币','热狗','大侠','御姐','萝莉','毛巾','期待','盼望','白昼','黑夜','大门','黑裤','钢铁侠','哑铃','板凳','枫叶','荷花','乌龟','仙人掌','衬衫','大神','草丛','早晨','心情','茉莉','流沙','蜗牛','战斗机','冥王星','猎豹','棒球','篮球','乐曲','电话','网络','世界','中心','鱼','鸡','狗','老虎','鸭子','雨','羽毛','翅膀','外套','火','丝袜','书包','钢笔','冷风','八宝粥','烤鸡','大雁','音响','招牌','胡萝卜','冰棍','帽子','菠萝','蛋挞','香水','泥猴桃','吐司','溪流','黄豆','樱桃','小鸽子','小蝴蝶','爆米花','花卷','小鸭子','小海豚','日记本','小熊猫','小懒猪','小懒虫','荔枝','镜子','曲奇','金针菇','小松鼠','小虾米','酒窝','紫菜','金鱼','柚子','果汁','百褶裙','项链','帆布鞋','火龙果','奇异果','煎蛋','唇彩','小土豆','高跟鞋','戒指','雪糕','睫毛','铃铛','手链','香氛','红酒','月光','酸奶','银耳汤','咖啡豆','小蜜蜂','小蚂蚁','蜡烛','棉花糖','向日葵','水蜜桃','小蝴蝶','小刺猬','小丸子','指甲油','康乃馨','糖豆','薯片','口红','超短裙','乌冬面','冰淇淋','棒棒糖','长颈鹿','豆芽','发箍','发卡','发夹','发带','铃铛','小馒头','小笼包','小甜瓜','冬瓜','香菇','小兔子','含羞草','短靴','睫毛膏','小蘑菇','跳跳糖','小白菜','草莓','柠檬','月饼','百合','纸鹤','小天鹅','云朵','芒果','面包','海燕','小猫咪','龙猫','唇膏','鞋垫','羊','黑猫','白猫','万宝路','金毛','山水','音响');

    $tou_num=rand(0,331);

    $wei_num=rand(0,325);

    $nicheng=$nicheng_tou[$tou_num].$nicheng_wei[$wei_num];

    return $nicheng;
}


/**
 * 随机抽奖
 * @param $proArr 奖项中奖率数组
 * @return int|string
 */
 function get_rand($proArr) {
    $result = '';

    //概率数组的总概率精度
    $proSum = array_sum($proArr);

    //概率数组循环
    foreach ($proArr as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $proCur) {
            $result = $key;
            break;
        } else {
            $proSum -= $proCur;
        }
    }
    unset ($proArr);

    return $result;
}


/**
 * 生成随机手机号
 * @param $n 生成个数
 * @param int $isHidden 是否要隐藏中间四位 1是0否
 * @return array
 */
function randomMobile($n,$isHidden = 1)
{
    $tel_arr = array(
        '130','131','132','133','134','135','136','137','138','139','144','147','150','151','152','153','155','156','157','158','159','176','177','178','180','181','182','183','184','185','186','187','188','189',
    );
    for($i = 0; $i < $n; $i++) {

        if($isHidden){
            $tmp[] = $tel_arr[array_rand($tel_arr)].'****'.mt_rand(1000,9999);
        }else{
            $tmp[] = $tel_arr[array_rand($tel_arr)].mt_rand(1000,9999).mt_rand(1000,9999);
        }


    }
    return array_unique($tmp);
}


/**
 * 匹配http链接中顶级域名
 * @param $url
 * @return string
 */
function getTopHost($url){
    $url = strtolower($url);  //首先转成小写
    $hosts = parse_url($url);
    $host = $hosts['host'];
    //查看是几级域名
    $data = explode('.', $host);
    $n = count($data);
    //判断是否是双后缀
    $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/';
    if(($n > 2) && preg_match($preg,$host)){
        //双后缀取后3位
        $host = $data[$n-3].'.'.$data[$n-2].'.'.$data[$n-1];
    }else{
        //非双后缀取后两位
        $host = $data[$n-2].'.'.$data[$n-1];
    }
    return $host;
}

/**
 * 随机数字生成
 * @param number $length 长度
 * @return unknown
 */
function generateNumber($length = 4)
{
    $min = pow(10 , ($length - 1));
    $max = pow(10, $length) - 1;
    
    $invitation_code = mt_rand($min, $max);
    
    return $invitation_code;
}


/**
 * 获取随机字符串
 * @param $length 指定长度
 * @return string
 */
function getRandom($length){
    $str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $key = "";
    for($i=0;$i<$length;$i++)
    {
        $key .= $str{mt_rand(0,32)};
    }
    return $key;
}


/**
 * 获取微妙时间戳
 * @return float
 */
function msectime() {
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;

}


/**
 * 通过数组查找最接近指定数字的数
 * @param $number 数字
 * @param $numberArray 数字列表
 * @return index 返回数组中的索引
 */
function getClosestNumberByArray($number, $numberArray){
    $w = 0;
    $c = -1;
    $abstand = 0;
    $l = count($numberArray);
    for($pos=0; $pos < $l; $pos++){
        $n = $numberArray[$pos];
        $abstand = ($n < $number) ? $number - $n : $n - $number;
        if ($c == -1){
            $c = $abstand;
            continue;
        }
        else if ($abstand < $c){
            $c = $abstand;
            $w = $pos;
        }
    }
    return $w;
}



function getMonthDay(){

    $days = date("t");

    for ($i = 0; $i < intval($days); $i++)
    {
        # 获取当月每天
        $day[] = date('Y-m-d', strtotime("+" .$i. " day", strtotime(date("Y-m-01"))));
    }


    return $day;
}


function buildPayHtml($endpoint, $payload)
{
    $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$endpoint."' method='POST'>";
    foreach ($payload as $key => $val) {
        $val = str_replace("'", '&apos;', $val);
        $sHtml .= "<input type='hidden' name='".$key."' value='".$val."'/>";
    }
    $sHtml .= "<input type='submit' value='ok' style='display:none;'></form>";
    $sHtml .= "<script>document.forms['alipaysubmit'].submit();</script>";
    return $sHtml;
}